﻿using Owin;
using Sustainalytics.ActiveMQHelper;
using Sustainalytics.FTPReport.BusinessLogic;
using Sustainalytics.Utils.Logging;
using System;
using System.Configuration.Abstractions;
using System.Web.Http;

namespace Sustainalytics.FTPReports.Service
{
    public class Startup
    {
        private bool generationInProgress;
        public void Configuration(IAppBuilder builder)
        {
            builder.UseAuthenticationServer();

            var config = new HttpConfiguration();
            config.Filters.Add(new SerilogControllerFilter());

            WebApiConfig.Register(config);
            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            builder.UseWebApi(config);

            config.EnsureInitialized();
            SubscribeToTopicEvents();
        }
        

        public void SubscribeToTopicEvents()
        {
            try
            {
                var settings = new ActiveMQAppSettings(ConfigurationManager.Instance.AppSettings, ConfigurationManager.Instance.ConnectionStrings);
                ITopicSubscriber activeMqTopicSubscriber = new ActiveMQTopicSubscriber(settings);

                activeMqTopicSubscriber.OnMessageReceived += ActiveMqTopicSubscriber_OnMessageReceived;
                Console.WriteLine("Waiting for SynchronizationFinished event ...");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private void ActiveMqTopicSubscriber_OnMessageReceived(object message)
        {
            if (generationInProgress)
                return;
            
            try
            {
                generationInProgress = true;
                var textMessage = message as string;
                TopicEvents outTopicEvents;
                var parse = Enum.TryParse<TopicEvents>(textMessage, out outTopicEvents);
                if (parse &&
                    (outTopicEvents == TopicEvents.SynchronizationFinished ||
                     outTopicEvents == TopicEvents.StartGenerateFTPReports))
                {
                    ReportsFtpManagement reportsFtpManagement = new ReportsFtpManagement();
                    reportsFtpManagement.StartGenerating();
                    Console.WriteLine("Generation starting");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                generationInProgress = false;
            }
            
        }
    }
}
